package ying.servlet;/**
 * ClassName: LoginServlet
 * Package: ying.servlet
 * Description:
 *
 * @Author 刘英杰
 * @Create 2024/9/29 19:09
 * @Version 1.0
 */

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import ying.bean.User;
import ying.utils.JDBCUtils;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取浏览器发送过来的参数
        //request.getParameter()方法中的name参数对应页面表单中name属性
        String username = request.getParameter("username");
        String password = request.getParameter("password");
//        System.out.println(username + " " + password);

        //2.利用DBUtils技术以及页面传递过来的用户名和密码去数据库中查询
        QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
        User user = null;
        try {
            user = qr.query("SELECT * FROM `user` WHERE username=? AND `password`=?", new BeanHandler<>(User.class), username, password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        //3.根据user对象,来判断
        //如果user为null,说明没有在数据库中查找到该用户,响应给浏览器登录失败
        //如果user不为null,说明在数据库中查找到该用户,响应给浏览器登录成功

        if (user != null) {
            response.getWriter().write("login succes");
        }else {
            response.getWriter().write("login failed");
        }
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
